package cn.oa.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.oa.dao.SystemPermissionMapper;
import cn.oa.dao.SystemUserinfoMapper;
import cn.oa.pojo.SystemPermission;
import cn.oa.pojo.SystemUserinfo;

@Controller
public class UserInfoController {

	@Resource(name = "systemUserinfoMapper")
	SystemUserinfoMapper systemUserinfoMapper;

	@Resource(name = "systemPermissionMapper")
	SystemPermissionMapper systemPermissionMapper;

	@RequestMapping("/toLogin")
	public String toLogin(HttpServletRequest request) {
		return "login";
	}

	@RequestMapping("/doLogin")
	public String doLogin(HttpServletRequest request, SystemUserinfo su) {
		SystemUserinfo sytemuserinfo = systemUserinfoMapper.login(su);
		if (sytemuserinfo != null) {
			request.getSession().setAttribute("USERS", sytemuserinfo);
			return "redirect:/index";
		}
		return "redirect:/toLogin";
	}

	/**
	 * 主界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		// 从当前session中获取会话信息
		SystemUserinfo sytemuserinfo = (SystemUserinfo) request.getSession().getAttribute("USERS");
		// 查询当前用户所能管理的菜单
		List<SystemPermission> list = systemPermissionMapper.getMenu(sytemuserinfo.getUserinfoUid());

		List<SystemPermission> listPermission = new ArrayList<>();

		for (SystemPermission sp : list) {
			if (sp.getParentId() == 0) {
				listPermission.add(sp);
			}
		}

		for (SystemPermission sp : list) {
			if (sp.getParentId() != 0) {
				for (SystemPermission sp2 : listPermission) {
					if (sp2.getPermissionId() == sp.getParentId()) {
						System.out.println(sp);
						sp2.getSecondPermission().add(sp);
					}
				}
			}

		}

		for (SystemPermission sp : listPermission) {
			System.out.println(sp.getPermissionName() + "\t" + sp.getSecondPermission().size());
			for (SystemPermission sp2 : sp.getSecondPermission()) {
				System.out.println("\t" + sp2.getPermissionName());
			}
		}

		request.getSession().setAttribute("list", listPermission);
		return "index";
	}

}
